package cn.magictodo.weblog.admin.service.impl;

import cn.magictodo.weblog.admin.model.vo.tag.*;
import cn.magictodo.weblog.admin.service.AdminTagService;
import cn.magictodo.weblog.common.domain.dos.ArticleTagRelDO;
import cn.magictodo.weblog.common.domain.dos.TagDO;
import cn.magictodo.weblog.common.domain.mapper.ArticleTagRelMapper;
import cn.magictodo.weblog.common.domain.mapper.TagMapper;
import cn.magictodo.weblog.common.enums.ResponseCodeEnum;
import cn.magictodo.weblog.common.exception.BizException;
import cn.magictodo.weblog.common.model.vo.SelectRspVO;
import cn.magictodo.weblog.common.utils.PageResponse;
import cn.magictodo.weblog.common.utils.Response;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 标签服务实现类
 *
 * @author liu
 * #time 2023-11-21 20:57
 */
@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagRelMapper articleTagRelMapper;

    /**
     * 添加标签列表
     *
     * @param addTagReqVO
     * @return
     */
    @Override
    public Response addTags(AddTagReqVO addTagReqVO) {
        List<TagDO> tags = addTagReqVO.getTags().stream().
                map(tagName -> TagDO.builder()
                        .name(tagName.trim())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build())
                .collect(Collectors.toList());

        try {
            saveBatch(tags);
        } catch (Exception e) {
            log.warn("添加标签失败,标签已存在", e);
        }

        return Response.success();
    }

    /**
     * 获取分页标签列表
     *
     * @param findTagPageListReqVO
     * @return
     */
    @Override
    public PageResponse findTagList(FindTagPageListReqVO findTagPageListReqVO) {
        // 获取当前页、以及每页需要展示的数据数量
        Long current = findTagPageListReqVO.getCurrent();
        Long size = findTagPageListReqVO.getSize();
        String name = findTagPageListReqVO.getName();
        LocalDate startDate = findTagPageListReqVO.getStartDate();
        LocalDate endDate = findTagPageListReqVO.getEndDate();

        Page<TagDO> tagDOPage = tagMapper.selectPageList(current, size, name,
                startDate, endDate);

        List<TagDO> tagDOList = tagDOPage.getRecords();
        List<FindTagPageListRspVO> tagDOListRsp = null;
        //判断是否为空
        if (!CollectionUtils.isEmpty(tagDOList)) {
            tagDOListRsp = tagDOList.stream().map(tagDO -> FindTagPageListRspVO.builder()
                            .name(tagDO.getName())
                            .id(tagDO.getId())
                            .articlesTotal(tagDO.getArticlesTotal())
                            .publishArticlesTotal(tagDO.getPublishArticlesTotal())
                            .createTime(tagDO.getCreateTime())
                            .build())
                    .collect(Collectors.toList());
        }

        return PageResponse.success(tagDOPage, tagDOListRsp);
    }

    /**
     * 删除标签
     *
     * @param deleteTagReqVO
     * @return
     */
    @Override
    public Response deleteTag(DeleteTagReqVO deleteTagReqVO) {

        Long tagId = deleteTagReqVO.getId();
// 校验该标签下是否有关联的文章，若有，则不允许删除，提示用户需要先删除标签下的文章
        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneByTagId(tagId);

        if (Objects.nonNull(articleTagRelDO)) {
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", tagId);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }

        int i = tagMapper.deleteById(tagId);

        return i == 1 ? Response.success() : Response.fail(ResponseCodeEnum.TAG_NOT_EXISTED);
    }

    /**
     * 模糊查询标签
     *
     * @param searchTagReqVO
     * @return
     */
    @Override
    public Response SearchTag(SearchTagReqVO searchTagReqVO) {
        String key = searchTagReqVO.getKey();

        List<TagDO> tagDOList = tagMapper.selectByKey(key);

        List<SelectRspVO> doS = null;
        if (!CollectionUtils.isEmpty(tagDOList)) {
            doS = tagDOList.stream().map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }

        return Response.success(doS);
    }


    /**
     * 获取标签下拉列表
     *
     * @return
     */
    @Override
    public Response findTagSelectList() {
        // 查询所有标签, Wrappers.emptyWrapper() 表示查询条件为空
        List<TagDO> tagDOS = tagMapper.selectList(Wrappers.emptyWrapper());

        // DO 转 VO
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }

        return Response.success(vos);
    }
}


